<?php
/**
 * Dirox Framework
 * Copyright (C) 2005 - 2007 Dirox / Synexser
 * 
 * All rights reserved.
 */
 
require_once 'HTML/QuickForm.php';
require_once('HTML/QuickForm/Renderer/ArraySmarty.php');

class DRX_QuickForm extends HTML_QuickForm {
	var $ajax;
	var $object;
	var $callback;
	var $renderer;
	
	private function ajaxQuickForm(&$formAttributes)
	{
		if (is_array($formAttributes)) {
			$onsubmit = $formAttributes['onsubmit'];
			$onsubmit = preg_replace(
				'/return myValidator\\(this\\);/',
				"if (myValidator(this)) quickform_ajax_submit('$this->object','$this->callback',this); return false;",
				 $onsubmit);
			$formAttributes['onsubmit'] = $onsubmit;
		} else if (is_string($formAttributes)) {
			$formAttributes = preg_replace(
				'/return myValidator\\(this\\);/',
				"if (myValidator(this)) quickform_ajax_submit('$this->object','$this->callback',this); return false;",
				 $formAttributes);
		}
	}
	
	function toArray()
	{
		if (isset($this->renderer)) {
			$arr = $this->renderer->toArray();
			if ($this->ajax === true) {
				$this->ajaxQuickForm($arr['attributes']);
			}

			return $arr;
		} else {
			if ($this->ajax === true) {
				$this->ajaxQuickForm($this->_attributes);
			}
			
			return parent::toArray();
		}
	}
	
	function toHtml()
	{
		if ($this->ajax === true) {
			$this->ajaxQuickForm();
		}
		return parent::toHtml();
	}
	
	function useSmarty($smarty)
	{
		$this->renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
       	
       	$this->renderer->setRequiredTemplate('
       		<{strip}>
				<span class="<{if $error}>error<{/if}> <{if $required}>required<{/if}>">
					<{if $error}>Warning: <{$error|strip_tags|escape}><{/if}> <{$label}>
				</span>
			<{/strip}>
		');
       	
       	$this->renderer->setErrorTemplate('<{$html}>');

       	$this->accept($this->renderer);
	}
}